const financialService = require('../../../services/financial');
const calculator = require('../../../utils/calculator');

Page({
  data: {
    loading: true,
    currentYear: new Date().getFullYear(),
    stats: {
      yearlyProfit: 0,          // 年度收益
      yearlyRate: 0,            // 年度收益率
      monthlyProfit: [],        // 月度收益
      monthlyRate: [],          // 月度收益率
      typeDistribution: {       // 类型分布
        fund: 0,
        deposit: 0,
        financial: 0
      }
    },
    lineOpts: {
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['收益金额', '收益率']
      },
      xAxis: {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
      },
      yAxis: [
        {
          type: 'value',
          name: '收益金额',
          position: 'left'
        },
        {
          type: 'value',
          name: '收益率',
          position: 'right',
          axisLabel: {
            formatter: '{value}%'
          }
        }
      ],
      series: [
        {
          name: '收益金额',
          type: 'bar',
          data: []
        },
        {
          name: '收益率',
          type: 'line',
          yAxisIndex: 1,
          data: []
        }
      ]
    },
    pieOpts: {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [{
        type: 'pie',
        radius: '50%',
        data: [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }]
    }
  },

  onLoad() {
    this.loadData();
  },

  onPullDownRefresh() {
    this.loadData();
  },

  async loadData() {
    try {
      this.setData({ loading: true });
      
      // 获取年度统计数据
      const yearlyStats = await financialService.getYearlyStats(this.data.currentYear);
      
      // 获取月度统计数据
      const monthlyStats = await financialService.getMonthlyStats(this.data.currentYear);
      
      // 获取类型分布数据
      const typeStats = await financialService.getTypeStats(this.data.currentYear);

      // 处理数据
      const stats = this.processStats(yearlyStats, monthlyStats, typeStats);
      
      this.setData({
        stats,
        loading: false
      });

      // 更新图表
      this.updateCharts();
    } catch (error) {
      console.error('加载数据失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      });
    } finally {
      wx.stopPullDownRefresh();
    }
  },

  processStats(yearlyStats, monthlyStats, typeStats) {
    // 处理年度数据
    const yearlyProfit = yearlyStats.profit || 0;
    const yearlyRate = yearlyStats.rate || 0;

    // 处理月度数据
    const monthlyProfit = new Array(12).fill(0);
    const monthlyRate = new Array(12).fill(0);
    
    monthlyStats.forEach(item => {
      const monthIndex = new Date(item.date).getMonth();
      monthlyProfit[monthIndex] = item.profit;
      monthlyRate[monthIndex] = item.rate;
    });

    // 处理类型分布
    const typeDistribution = {
      fund: typeStats.fund || 0,
      deposit: typeStats.deposit || 0,
      financial: typeStats.financial || 0
    };

    return {
      yearlyProfit,
      yearlyRate,
      monthlyProfit,
      monthlyRate,
      typeDistribution
    };
  },

  updateCharts() {
    const { monthlyProfit, monthlyRate, typeDistribution } = this.data.stats;
    
    // 更新折线图数据
    this.setData({
      'lineOpts.series[0].data': monthlyProfit,
      'lineOpts.series[1].data': monthlyRate
    });

    // 更新饼图数据
    const pieData = [
      { name: '基金', value: typeDistribution.fund },
      { name: '存款', value: typeDistribution.deposit },
      { name: '银行理财', value: typeDistribution.financial }
    ];
    
    this.setData({
      'pieOpts.series[0].data': pieData
    });
  },

  // 切换年份
  changeYear(e) {
    const year = e.currentTarget.dataset.year;
    this.setData({
      currentYear: year
    }, () => {
      this.loadData();
    });
  }
}); 